package wk.asm.test;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by wangkuan at 2018-09-11 9:17
 */
public class MyEnhancer {

    public static void main(String[] args) {
        Tester tester = new MyEnhancer().getProxy(Tester.class);
        tester.run();
        tester.sleep();
    }

    @SuppressWarnings("all")
    public <T> T getProxy(Class<T> tClass) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(tClass);
        enhancer.setCallback(new MyCallback());
        enhancer.setClassLoader(tClass.getClassLoader());

        return (T)enhancer.create();
    }

    public class MyCallback implements MethodInterceptor {

        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("=============");

            Object result = methodProxy.invokeSuper(o, objects);

            System.out.println("+++++++++++++");

            return result;
        }
    }

}
